<template>
  <Category :scene="scene"></Category>

  <el-card class="box-card-bottom">
    <template v-if="scene === 0">
      <el-button @click="addAttr" :disabled="category.c3Id ? false : true" type="primary" icon="Plus">添加属性</el-button>
      <el-table class="elTable" :data="attrArr" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="attrName" label="属性名称" width="120" align="center" />
        <el-table-column prop="attrValueList" label="属性值名称" align="center">
          <template #default="{ row, $index }">
            <el-tag v-for="item in row.attrValueList" :key="item.id" type="primary">{{ item.valueName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row, $index }">
            <el-button @click="updateAttr(row)" type="warning" size="small" icon="Edit" circle></el-button>
            <el-button @click="deleteAttr(row)" type="danger" size="small" icon="Delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template v-else-if="scene === 1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input v-model="attrParams.attrName" placeholder="请输入属性名称"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="addAttrValue" :disabled="attrParams.attrName === '' ? true : false" type="primary" icon="Plus">添加属性值</el-button>
      <el-button type="default" @click="cancel">取消</el-button>
      <el-table class="elAddTable" :data="attrParams.attrValueList" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="valueName" label="属性值名称">
          <!--  
            <template #default="{ row, $index }"> 
              $index前面的$不能少，不然获取不到index值
            </template>
            -->
          <template #default="{ row, $index }">
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-if="row.flag"
              @blur="toLock(row, $index)"
              v-model="row.valueName"
              placeholder="请输入属性值名称"
            ></el-input>
            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button @click="deleteAttrValue($index)" type="danger" size="small" icon="Delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="saveAttrValue" :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
      <el-button type="default" @click="cancel">取消</el-button>
    </template>
  </el-card>
</template>

<script setup lang="ts">
import { Attr, AttrList, AttrResponseData, AttrValue } from '@/api/product/attr/types';
import { ElMessageBox } from 'element-plus';

// 三级分类仓库
const category = useCategoryStore();
// 属性数组
const attrArr = ref<AttrList>([]);
// 是否切换到添加或者编辑场景
const scene = ref<number>(0);
// 输入框的ref
const inputArr = ref<any>([]);
// 属性的参数
const attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
});

// c3Id改变加载数据
watch(
  () => category.c3Id,
  () => {
    getAttr();
  },
);
const getAttr = async () => {
  if (!category.c3Id) return;
  const result: AttrResponseData = await reqGetAttrInfo(category.c1Id, category.c2Id, category.c3Id);
  if (result.code === 200) {
    attrArr.value = result.data;
  }
};
//添加属性
const addAttr = () => {
  scene.value = 1;
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: category.c3Id,
    categoryLevel: 3,
  });
};
//更新属性
const updateAttr = (row: Attr) => {
  scene.value = 1;
  //将已有的属性对象赋值给attrParams对象即为
  //ES6->Object.assign进行对象的合并
  // 必须使用深拷贝，JSON.parse(JSON.stringify(row))
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};
//添加属性值
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  });
  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};
//保存属性值
const saveAttrValue = async () => {
  const result: any = await reqAddAttrInfo(attrParams);
  if (result.code === 200) {
    ElMessage.success(attrParams.id ? '更新成功' : '添加成功');
    getAttr();
    scene.value = 0;
  } else {
    ElMessage.error(attrParams.id ? '更新失败' : '添加失败');
  }
};
//取消
const cancel = () => {
  scene.value = 0;
};
//删除属性
const deleteAttr = (row: Attr) => {
  ElMessageBox.confirm(`确定要删除【${row.attrName}】这个商品属性吗？`, { title: '提示' })
    .then(async () => {
      const result: any = await reqDeleteAttrInfo(row.id as number);
      if (result.code === 200) {
        ElMessage.success('删除成功');
        getAttr();
      } else {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {
      ElMessage.success('已取消删除');
    });
};
//删除属性值
const deleteAttrValue = ($index: number) => {
  attrParams.attrValueList.splice($index, 1);
};
//输入框失去焦点触发
const toLock = (row: AttrValue, $index: number) => {
  if (row.valueName.trim().length === 0) {
    attrParams.attrValueList.splice($index, 1);
    ElMessage.error('属性值不能为空');
    return;
  }

  let repeat = attrParams.attrValueList.find((item) => {
    if (item !== row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    attrParams.attrValueList.splice($index, 1);
    ElMessage.error('属性值不能重复');
    return;
  }
  row.flag = false;
};
// 点击div触发
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
</script>

<style lang="scss" scoped>
.box-card-bottom {
  margin-top: 10px;
  .elTable {
    margin-top: 10px;
    height: calc(100vh - $base-tabbar-height - 188px);
  }
  .elAddTable {
    margin: 10px 0;
  }
}
</style>
